package com.fwixvye.utils;

import com.fwixvye.pojo.OcrRequestBody;
import com.fwixvye.pojo.OcrResponseBody;

import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.Base64;
import java.util.HashMap;
import java.util.Objects;


public class OcrUtil {

    /**将图片转换成文字
     * @param file 前端传过来的图片
     * @param restTemplate  service传过来的 请求类
     * @return 返回一个OcrResponseBody
     * @throws IOException  抛出异常
     */
    public OcrResponseBody ImageToOcrResponseBody(MultipartFile file, RestTemplate restTemplate) throws IOException {

        long size = file.getSize();

        InputStream inputStream = lumAdjustment(file, -50);

        String url = "http://127.0.0.1:1224/api/ocr";

        OcrRequestBody ocrRequestBody = new OcrRequestBody();

        byte[] buffer = new byte[(int) size];
        inputStream.read(buffer);
        inputStream.close();

        String imgBase64 = Base64.getEncoder().encodeToString(buffer);
        ocrRequestBody.setBase64(imgBase64);

        try {
            return restTemplate.postForObject(url, ocrRequestBody, OcrResponseBody.class);
        } catch (Exception e) {
            return null;
        }

    }

    /**
     * 图片亮度调整
     *
     * @param file 前端传来的图片
     * @param param 变多亮的参数
     * @throws IOException 抛出异常
     */
    public InputStream lumAdjustment(MultipartFile file, int param) throws IOException {
        InputStream inputStream = file.getInputStream();
        BufferedImage image = ImageIO.read(inputStream);
        if (image == null) {
            return null;
        } else {
            int rgb, R, G, B;
            for (int i = 0; i < image.getWidth(); i++) {
                for (int j = 0; j < image.getHeight(); j++) {
                    rgb = image.getRGB(i, j);
                    R = ((rgb >> 16) & 0xff) + param;
                    G = ((rgb >> 8) & 0xff) + param;
                    B = (rgb & 0xff) + param;

                    rgb = ((clamp(255) & 0xff) << 24) | ((clamp(R) & 0xff) << 16) | ((clamp(G) & 0xff) << 8)
                            | ((clamp(B) & 0xff));
                    image.setRGB(i, j, rgb);
                }
            }
        }
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();



        String[] strings = Objects.requireNonNull(file.getOriginalFilename()).split("\\.");
        String suffix = strings[strings.length - 1];

        ImageIO.write(image, suffix, outputStream);
        byte[] imageBytes = outputStream.toByteArray();
        InputStream arrayInputStream = new ByteArrayInputStream(imageBytes);
        return arrayInputStream;

    }

    // 判断a,r,g,b值，大于256返回256，小于0则返回0,0到256之间则直接返回原始值
    private int clamp(int rgb) {
        if (rgb > 255)
            return 255;
        if (rgb < 0)
            return 0;
        return rgb;
    }



}
